<?php
namespace App\Admin\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Carbon;
use App\Admin\Controllers\Controller;
use App\Admin\Requests\TokenCreateRequest;
use App\Admin\Admin;
use App\Admin\Agent;

class TokenController extends Controller
{

	// http://localhost:8848/api/admin/token
	public function index(Request $request)
	{
        $models = DB::table('system_user_session')->where('user_id', Admin::user()->id)->get();

        $models->map(function($model){
        	$agent = new Agent();
        	$agent->setUserAgent($model->user_agent);


        	$model->is_current_device = ($model->id == Admin::getAuthorization());
        	$model->last_active = Carbon::create($model->last_activity)->diffForHumans();
        	$model->location    = Admin::location($model->ip_address);
        	$model->agent = [
    			'is_desktop' => $agent->isDesktop(), 
    			'platform'   => $agent->platform(),
    			'browser'    => $agent->browser(),
        	];
        });

		return Admin::success([
			'total' => $models->count(),
			'data' => $models,
		]);
	}

	/**
	 * 创建Token[登录]
	 */
	public function store(TokenCreateRequest $request)
	{
		// 鉴定用户账号和密码
		$request->authenticate();

		// 生成token
		$token = $request->generateToken();

		// 写登录记录和IP
		$request->record();

		return $this->success(['token'=>$token]);
	}


	/**
	 * 销毁Token[退出]
	 */
	public function destroy(Request $request)
	{
		$currentToken = Admin::getAuthorization();
		$is_logout = $request->has('logout');

		if( $is_logout ){
			// 仅退出当前设备
			Redis::del($currentToken);
			$models = DB::table('system_user_session')->where('id', $currentToken)->delete();
			return Admin::success(null, 0, 'logout is success');
		}

		$models = DB::table('system_user_session')
			->where('user_id', Admin::user()->id)
			->where('id', '<>', $currentToken)
			->get();


		if( $models->count() != 0 ){
			$kes = $models->pluck('id');
			Redis::delete(...$kes);
			$models = DB::table('system_user_session')
				->whereIn('id', $kes)
				->delete();
		}

		return Admin::success($models, 0, '已退出所有其他设备');
	}

}
